package top.fzqblog.action;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.fzqblog.Utils.R;
import top.fzqblog.exception.BizException;
import top.fzqblog.model.Prize;
import top.fzqblog.model.User;
import top.fzqblog.model.UserPrize;
import top.fzqblog.service.UserPrizeService;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by 抽离 on 2017/9/1 0001.
 */
@Controller
public class UserPrizeAction extends BaseAction{

    @Autowired
    private UserPrizeService userPrizeService;

    @RequestMapping("/userPrizeList")
    public String userPrizeList(HttpSession session){
        if(getCurrentUser(session) == null){
            return "login";
        }
        return "/system/userPrizeList";
    }

    @ResponseBody
    @RequestMapping("getUserPrizeList")
    public R getUserPrizeList(HttpSession session, int page, int limit) {
        if(getCurrentUser(session) == null){
            return R.error("请先登录！");
        }
        Page<UserPrize> userPrizePage = new Page<>();
        userPrizePage.setCurrent(page);
        userPrizePage.setSize(limit);
        Page<UserPrize> p = new UserPrize().selectPage(userPrizePage, new EntityWrapper<UserPrize>().orderBy("status").orderBy("create_time", false));
        return R.ok().put("count", p.getTotal()).put("data", p.getRecords());
    }

    @RequestMapping("addUserPrize")
    @ResponseBody
    public R addUserPrize(HttpSession session, Integer prizeId){
        if(checkWxLogin(session)){
            User user = getCurrentWxUser(session);
            try {
                userPrizeService.addUserPrize(user, prizeId);
                return R.ok();
            } catch (BizException e) {
                return R.error(e.getLocalizedMessage());
            }
        }
        return R.error("请先登录！");
    }


    @RequestMapping("wxUserPrize")
    public String getUserPrizes(HttpSession session, Model model){
        if(!checkWxLogin(session)){
            return "/wx/login";
        }
        User user = getCurrentWxUser(session);
        List<UserPrize> list = new UserPrize()
                .selectList(new EntityWrapper<UserPrize>().eq("user_id", user.getUserId()));
        model.addAttribute("list", list);
        return "/wx/userprize";
    }


    @ResponseBody
    @RequestMapping("confirmDui")
    public R ConfirmDui(HttpSession session, Integer id){
        if(getCurrentUser(session) == null){
            return R.error("请先登录！");
        }
        try {
            userPrizeService.ConfirmDui(id);
        } catch (BizException e) {
            return R.error(e.getLocalizedMessage());
        }
        return R.ok();
    }
}
